package cn.stylefeng.guns.modular.demos.mapi;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import cn.stylefeng.roses.core.base.controller.BaseController;

//@RestController
@Controller
@RequestMapping("/mappApi")
public class FileController extends BaseController{
	   //private final static String rootPath = "D://data/";
	   
	   @Value("${zdcl.upimg}")
	   private String upimgPath;
	   
	   private Logger log = LoggerFactory.getLogger(this.getClass());

	   
    
	   
	   @RequestMapping(value="/upload", method=RequestMethod.POST)
	   public ResponseEntity upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
	        String suffixName = null;

	        HashMap<String, Object> urlPath = new HashMap<>();
	        
	        //log.debug("文件名XXX： " + rootPathc);
	        
	        /*
	        final String requestHeader = request.getHeader(JwtConstants.AUTH_HEADER);
			String authToken;
			if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
			    authToken = requestHeader.substring(7);
			    
			    log.debug(authToken);
			   String openid = JwtTokenUtil.getPrivateClaimFromToken(authToken,"openid");
			   String sessionKey = JwtTokenUtil.getPrivateClaimFromToken(authToken,"sessionKey");
			   log.debug(openid);
			   log.debug(sessionKey);
			  // wUserService.wxUpdateUserInfo(openid,sessionKey,info);
			}
	        */
	        Date curDate = new Date();
	        String newPath = "";
	        newPath+=curDate.getYear()+1900;
	        newPath += "/";
	        newPath += (curDate.getMonth() +1)< 10 ? "0"+(curDate.getMonth() +1) : (curDate.getMonth()+1);
	        newPath += "/";
	        newPath += curDate.getDate() < 10 ? "0"+curDate.getDate() : curDate.getDate();
	        newPath += "/";
	        newPath += curDate.getHours()< 10 ? "0"+curDate.getHours() : curDate.getHours();
	        newPath += "/";
	        // 文件名
	        try{
		        String fileName = file.getOriginalFilename();
		        log.debug("文件名： " + fileName);
	
		        // 文件后缀
		        suffixName = fileName.substring(fileName.lastIndexOf("."));
		        log.debug("文件后缀名： " + suffixName);
	        }catch(Exception e){
	        	 return new ResponseEntity<>("上传失败", HttpStatus.SERVICE_UNAVAILABLE);
	        }

	        // 重新生成唯一文件名，用于存储数据库
	        newPath += (UUID.randomUUID().toString()+suffixName);
	        System.out.println("新的文件名： " + newPath);
	        
	        //创建文件
	        File dest = new File(upimgPath + newPath);
	        //路径不存在创建路径
	        File fileParent = dest.getParentFile();  
	        if(!fileParent.exists()){  
	            fileParent.mkdirs();  
	        }  

	        try {
	            file.transferTo(dest);
	            urlPath.put("urlPath", newPath);
	            urlPath.put("msg", "上传成功");
	            return new ResponseEntity<>(urlPath, HttpStatus.OK);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        urlPath.put("msg", "上传失败");
	        return new ResponseEntity<>(urlPath, HttpStatus.SERVICE_UNAVAILABLE);
	    }

	   /*
	    * 批量上传
	    * 
	    */
	   @SuppressWarnings("rawtypes")
	   @RequestMapping(value="/batch/upload", method=RequestMethod.POST) 
	   public ResponseEntity handleFileUpload(HttpServletRequest request){ 
	        List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("file"); 
	        MultipartFile file = null;
	        String newFileName = null;
	        HashMap<String, Object> urlPath = new HashMap<>();
	        List<String> urlPaths = new ArrayList();
	        
	        log.debug("/batch/upload files:"+files.size());
	        
	        Date curDate = new Date();
	        String newPath = "";
	        newPath+=curDate.getYear()+1900;
	        newPath += "/";
	        newPath += (curDate.getMonth() +1)< 10 ? "0"+(curDate.getMonth() +1) : (curDate.getMonth()+1);
	        newPath += "/";
	        newPath += curDate.getDate() < 10 ? "0"+curDate.getDate() : curDate.getDate();
	        newPath += "/";
	        newPath += curDate.getHours()< 10 ? "0"+curDate.getHours() : curDate.getHours();
	        newPath += "/";
	        
	        
	        BufferedOutputStream stream = null;
	        for (int i =0; i< files.size(); ++i) { 
	            file = files.get(i); 
	            
	            // 文件名
	            String fileName = file.getOriginalFilename();
	            log.debug("文件名： " + fileName);
	            
	            if("".equals(fileName)){
	            	continue;
	            }
	            
	            try{
		            // 文件后缀
			        String suffixName = fileName.substring(fileName.lastIndexOf("."));
			        log.debug("文件后缀名： " + suffixName);
			        
			        // 重新生成唯一文件名，用于存储数据库
			        newFileName = newPath + UUID.randomUUID().toString()+suffixName;
			        
			        urlPaths.add(newFileName);
			        System.out.println("新的文件名： " + newFileName);
	            }catch(Exception e){
	            	 return new ResponseEntity<>("文件名解析失败", HttpStatus.SERVICE_UNAVAILABLE);
	            }

		        //创建文件
		        File dest = new File(upimgPath + newFileName);
		        File fileParent = dest.getParentFile();  
		        if(!fileParent.exists()){
		            fileParent.mkdirs();  
		        }  
		        
		        if (!file.isEmpty()) { 
		        	 try {
		 	            file.transferTo(dest);
		 	        } catch (IOException e) {
		 	            e.printStackTrace();
		 	           return new ResponseEntity<>("上传失败", HttpStatus.SERVICE_UNAVAILABLE);
		 	        }
		        }
	        } 
	        urlPath.put("urlPath", urlPaths);
	        urlPath.put("msg", "上传成功");
	        return new ResponseEntity<>(urlPath, HttpStatus.OK);
	    } 
	   
     
}
